<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/26
 * Time: 13:30
 */
namespace Modules;

use Admin\Models\crm\XhcustInfo;
use Admin\Models\overt\XhovertAreainfo;
use Helpers\Tool;
use Helpers\XhException;
use Phalcon\Di;
use Phalcon\Paginator\Adapter\QueryBuilder;

class Customer
{
    //returnType
    public const TYPE_EASYUI = 1;
    public const TYPE_KEYVALUE = 2;


    /**
     * 获取客户名称
     *
     * @return array
     *
     * create by dale  20181126
     */
    public static function getCustomerNames()
    {
        $infoArr = XhcustInfo::find([
            'columns'    => 'iCUId as id,sSchoolName as name',
            'conditions' => 'bDelete= 0'
        ])->toArray();
        if (!$infoArr) {
            return [];
        }
        return $infoArr;
    }

    /**
     * 根据学校id获取学校名称
     *
     * @param $schoolId
     *
     * @return string
     *
     * create by dale  20190115
     */
    public static function getSchoolNameBySchoolId($schoolId)
    {
        $info = XhcustInfo::findFirst([
            'columns'    => 'sSchoolName,iSchoolId',
            'conditions' => 'bDelete= 0 and iSchoolId = :iSchoolId:',
            'bind'       => ['iSchoolId' => $schoolId]
        ]);
        if (!$info) {
            return '';
        }
        return $info->sSchoolName;
    }

    /**
     * 获取学校id
     *
     * @param $custId
     *
     * @return int
     * @throws XhException
     *
     * create by dale  20181126
     */
    public static function getSchoolId($custId)
    {

        if (!$custId) {
            throw new XhException('没有传入id');
        }
        $info = XhcustInfo::findFirst([
            'columns'    => 'iSchoolId',
            'conditions' => 'bDelete = 0 and iCUId = :iCUId:',
            'bind'       => ['iCUId' => $custId]
        ]);
        if (!$info) {
            throw new XhException('未找到该客户');
        }
        if (!$info->iSchoolId) {
            throw new XhException('该客户未关联学校id');
        }
        return $info->iSchoolId;
    }

    /**
     * 根据学校id获取客户id
     *
     * @param $schoolId
     *
     * @return int
     * @throws XhException
     *
     * create by dale  20181127
     */
    public static function getCustId($schoolId)
    {
        if (!$schoolId) {
            throw new XhException('没有传入id');
        }
        $info = XhcustInfo::findFirst([
            'columns'    => 'iCUId',
            'conditions' => 'iSchoolId = :iSchoolId: and bDelete = 0 ',
            'bind'       => ['iSchoolId' => $schoolId]
        ]);
        if (!$info) {
            throw new XhException('未找到该客户');
        }
        if (!$info->iCUId) {
            throw new XhException('该客户未关联学校id');
        }
        return $info->iCUId;
    }

    /**
     * 根据学校id获取客户id,批量
     *
     * @param array $schoolIdArr
     *
     * @return array
     * @throws XhException
     *
     * create by qgz 20181218
     */
    public static function getCustIdArr($schoolIdArr = [])
    {
        if (!$schoolIdArr) {
            throw new XhException('没有传入id');
        }
        $info = XhcustInfo::find([
            'columns'    => 'iCUId, iSchoolId',
            'conditions' => "iSchoolId in ({idArr:array}) and bDelete = 0 ",
            'bind'       => ['idArr' => array_values(array_filter(array_unique($schoolIdArr)))]
        ])->toArray();
        if (!$info) {
            return [];
        }
        return array_column($info, 'iCUId', 'iSchoolId');
    }

    /**
     * 获取客户学校列表
     *
     * @return XhcustInfo|XhcustInfo[]|array
     *
     * create by dale  20181227
     */
    public static function getCustSchoolArr()
    {
        $schools = XhcustInfo::find([  //学校
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete=0 AND iSchoolId is not null'
        ]);
        $schools = array_column($schools->toArray(), 'sSchoolName', 'iSchoolId');
        return $schools;
    }

    /**
     * 获取地区
     *
     * @param int $id
     * @param int $returnType
     *
     * @return array
     * @throws \Exception
     *
     * create by dale  20190111
     */
    public static function getArea($id = 0, $returnType = self::TYPE_EASYUI)
    {
        $area = XhovertAreainfo::find([
            'columns'    => 'areaCode,areaName',
            'conditions' => 'parentCode = :parentCode:',
            'bind'       => ['parentCode' => $id]
        ])->toArray();
        if ($returnType == self::TYPE_KEYVALUE) {
            return array_column($area, 'areaName', 'areaCode');
        } elseif ($returnType == self::TYPE_EASYUI) {
            if (!$area) {
                return [];
            }
            $easyuiArr = [];
            foreach ($area as $row) {
                $easyuiArr[] = [
                    'id'   => @$row['areaCode'],
                    'text' => @$row['areaName']
                ];
            }
            return $easyuiArr;
        } else {
            throw new \Exception('未知returnType类型');
        }
    }

    /**
     * 根据区域过滤客户的学校
     *
     * @param array $params
     *
     * @return array
     *
     * create by dale  20190114
     */
    public static function filterSchoolByArea($params = [])
    {
        $county = Tool::getValue($params, 'county');
        $city = Tool::getValue($params, 'city');
        $province = Tool::getValue($params, 'province');
        if ($county) {
            $custArr = XhcustInfo::find([
                'columns' => 'iCUId,iSchoolId,sSchoolName',
                'conditions' => 'bDelete = 0 and sCountyName = :sCountyName:',
                'bind' => ['sCountyName' => $county]
            ])->toArray();
            if (!$custArr) {
                throw new \Exception('未找到该区下的学校');
            }
        } elseif ($city) {
            $custArr = XhcustInfo::find([
                'columns' => 'iCUId,iSchoolId,sSchoolName',
                'conditions' => 'bDelete = 0 and sCityName = :sCityName:',
                'bind' => ['sCityName' => $city]
            ])->toArray();
            if (!$custArr) {
                throw new \Exception('未找到该市下的学校');
            }
        } elseif ($province) {
            $custArr = XhcustInfo::find([
                'columns' => 'iCUId,iSchoolId,sSchoolName',
                'conditions' => 'bDelete = 0 and sProvinceName = :sProvinceName:',
                'bind' => ['sProvinceName' => $province]
            ])->toArray();
            if (!$custArr) {
                throw new \Exception('未找到该省下的学校');
            }
        } else {
            return [];
        }
        return array_values(array_filter(array_unique(array_column($custArr, 'iSchoolId'))));
    }

    /**
     * 分页方法
     *
     * @param $builder
     * @param $page
     * @param $rows
     *
     * @return array
     *
     * create by dale  20190116
     */
    public static function runBuildPage($builder, $page, $rows)
    {
        $paginator = new QueryBuilder([
            'builder'   => $builder,
            'limit'     => $rows,
            'page'      => $page
        ]);
        @$paginator = $paginator->getPaginate();
        $total = $paginator->total_items;
        $rows  = $paginator->items->toArray();
        return ['total' => $total, 'rows' => $rows];
    }

    /**
     * 获取客户列表
     *
     * @param array $params
     * @param bool $isPageBuilder
     *
     * @return array
     * @throws \Exception
     *
     * create by dale  20190116
     */
    public static function getCustomerList($params = [], $isPageBuilder = true)
    {
        $page = Tool::getValue($params, 'page');
        $size = Tool::getValue($params, 'size');
        $fields = Tool::getValue($params, 'fields');
        $key = Tool::getValue($params, 'key');
        $county = Tool::getValue($params, 'county');
        $city = Tool::getValue($params, 'city');
        $province = Tool::getValue($params, 'province');
        $schoolIdNeeded = Tool::getValue($params, 'schoolIdNeeded', false);

        $custColumns =  array_keys(get_object_vars(new XhcustInfo()));
        //去除私有对象
        $custColumns = array_filter(array_map(function ($val) {
            if (strpos($val, '_') !== false) {
                return '';
            } else {
                return $val;
            }
        }, $custColumns));
        if ($fields) {
            $custColumns = array_intersect($custColumns, $fields);
        }
        $custColumns = array_map(function ($val) {
            return 'c.'.$val;
        }, $custColumns);
        $builder =  Di::getDefault()->get('modelsManager')->createBuilder()
            ->from(['c' => 'Admin\Models\crm\XhcustInfo'])
            ->columns(array_merge($custColumns, []))
            ->where('c.bDelete = 0');
        if ($schoolIdNeeded) {
            $builder->andWhere("iSchoolId is not null or iSchoolId <> ''");
        }
        if ($key) {
            $builder->andWhere("sSchoolName like :key: ", ['key' => '%'.$key.'%']);
        }
        if ($county) {
            $builder->andWhere("sCountyName = :sCountyName: ", ['sCountyName' => $county]);
        } elseif ($city) {
            $builder->andWhere("sCityName = :sCityName: ", ['sCityName' => $city]);
        } elseif ($province) {
            $builder->andWhere("sProvinceName = :sProvinceName: ", ['sProvinceName' => $province]);
        }
        if ($isPageBuilder) {
            if (!$page || !$size) {
                throw new \Exception('缺少分页条件page或者size');
            }
            $data = self::runBuildPage($builder, $page, $size);
        } else {
            $data = $builder->getQuery()->execute()->toArray();
        }
        return $data;
    }



}
